package jp.co.menox.tmapp.service;

import java.util.Random;

import jp.co.menox.tmapp.dto.SharingIdDto;
import jp.co.menox.tmcommon.common.DataConst;
import jp.co.menox.tmcommon.model.LendingHistory;
import jp.co.menox.tmserver.dao.LendingHistoryDao;

/**
 * 貸し借り履歴関連サービス
 * @author
 *
 */
public class LendingHistoryService extends TmAppServiceBase<LendingHistory, LendingHistoryDao> {

    public LendingHistoryService() {
        dao = new LendingHistoryDao();
    }
    
    // 借りる側：sharingId発行
    public SharingIdDto updateSharingId(long id) {
        Random random = new Random();
        int randomNumber = random.nextInt(1000000);
        String sharingId = String.format("%1$06d", randomNumber);
        
        LendingHistory model = dao.select(id);
        model.setSharingId(sharingId);
        
        LendingHistory resultModel = update(model);
        
        return new SharingIdDto(resultModel.getSharingId());
    }
    
    // 貸す側
    public boolean updateStatus(long id, int statusType, String sharingId) {
        LendingHistory model = dao.select(id);
        
        if (model.getSharingId().equals(sharingId)) {
            model.setStatusType(statusType);
            update(model);
            return true;
        } else {
            return false;
        }
    }
    
    public boolean checkConclusion(long id, int beforeStatus) {
        LendingHistory model = dao.select(id);
        
        if (beforeStatus == DataConst.STATUS_SYOUNINZUMI && 
                model.getStatusType() == DataConst.STATUS_KASHIDASHITYU) {
            return true;
        }
        
        if (beforeStatus == DataConst.STATUS_KASHIDASHITYU && 
                model.getStatusType() == DataConst.STATUS_HENKYAKUZUMI) {
            return true;
        }
        
        return false;
    }
    
    @Override
    public LendingHistory insert(LendingHistory model) {
        return super.insert(model);
    }

    @Override
    public LendingHistory update(LendingHistory model) {
        return super.update(model);
    }

    @Override
    public LendingHistory delete(LendingHistory model) {
        return super.delete(model);
    }

    
    // **** イベント処理用メソッド

    @Override
    public void onInserted(LendingHistory model) {
        super.onInserted(model);
    }

    @Override
    public void onUpdated(LendingHistory model) {
        super.onUpdated(model);
    }

    @Override
    public void onDeleted(LendingHistory model) {
        super.onDeleted(model);
    }
}